﻿using System;
using System.Windows.Forms;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using YArchitech.Revit;

namespace YArchitech.Plumbing
{
	[Transaction(TransactionMode.Manual)]
	public class SetSanitary : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			Result result;
			try
			{
				UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
				Document document = activeUIDocument.Document;
				SetSanitaryHelper setSanitaryHelper = new SetSanitaryHelper(activeUIDocument);
				SetSanitaryData setSanitaryData = null;
				Element element = null;
				FormSetSanitary formSetSanitary = null;
				bool flag = false;
				for (;;)
				{
					transaction = new Transaction(document, "定义洁具");
					transaction.Start();
					if (!flag)
					{
						element = setSanitaryHelper.GetSanitary();
						if (element == null)
						{
							break;
						}
						setSanitaryData = YJKRevitTools.GetSetSanitaryData(document, element);
						formSetSanitary = new FormSetSanitary(setSanitaryData, document);
						setSanitaryData = formSetSanitary.SanitaryData;
						flag = true;
					}
					formSetSanitary.ShowDialog();
					if (formSetSanitary.DialogResult == DialogResult.Abort)
					{
						int nChoose = formSetSanitary.nChoose;
						if (nChoose != 1)
						{
							if (nChoose == 2)
							{
								setSanitaryData.ColdPointVector = setSanitaryHelper.GetPoint("冷水", element);
							}
						}
						else
						{
							setSanitaryData.HotPointVector = setSanitaryHelper.GetPoint("热水", element);
						}
					}
					else
					{
						if (formSetSanitary.DialogResult != DialogResult.OK)
						{
							goto IL_D6;
						}
						setSanitaryHelper.WriteExtendData(setSanitaryData, element);
						flag = false;
					}
					transaction.Commit();
				}
				return Autodesk.Revit.UI.Result.Succeeded;
				IL_D6:
				transaction.Commit();
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex)
			{
				message = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				if (transaction != null)
				{
					TransactionStatus status = transaction.GetStatus();
					if ((int)status == 1)
					{
						transaction.Commit();
					}
					else if ((int)status == 5)
					{
						transaction.RollBack();
					}
				}
			}
			return result;
		}
	}
}
